package droid.frame.utils.android;

import android.annotation.SuppressLint;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import droid.frame.App;
import droid.frame.libcore.R;

/**
 * 项目用用到的toast统一调用
 *
 * @author coffee<br>
 *         2016-12-27下午4:24:47
 */
public class Alert {
    /**
     * @param msg
     */
    public static void toast(String msg, final int... shortOrLong) {
        // 默认显示toast
        if (shortOrLong == null || shortOrLong.length == 0) {
            toastInternal(msg, Toast.LENGTH_SHORT);
        } else {
            toastInternal(msg, shortOrLong[0]);
        }
    }

    public static void toast(int res) {
        String str = App.getContext().getResources().getString(res);
        toast(str);
    }

    @SuppressLint("InflateParams")
    private static void toastInternal(final String msg, final int shortOrLong) {
        App.getHandler().post(new Runnable() {
            @Override
            public void run() {
                // toast布局
                View layout = LayoutInflater.from(App.getContext()).inflate(R.layout.app_toast_common, null);
                TextView text = (TextView) layout.findViewById(R.id.toast_content);
                text.setText(msg);
                Toast toast = new Toast(App.getContext());
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.setDuration(shortOrLong);
                toast.setView(layout);
                toast.show();
            }
        });
    }

    /**
     * 带图片的toast
     *
     * @param msg
     * @param shortOrLong
     */
    public static void toastWithImage(final String msg, final int imageRes, final int... shortOrLong) {
        App.getHandler().post(new Runnable() {
            @Override
            public void run() {
                // toast布局
                View layout = LayoutInflater.from(App.getContext()).inflate(R.layout.app_toast_common, null);
                TextView text = (TextView) layout.findViewById(R.id.toast_content);
                ImageView imageView = (ImageView) layout.findViewById(R.id.toast_image);
                imageView.setVisibility(View.VISIBLE);
                imageView.setImageResource(imageRes);
                text.setText(msg);
                Toast toast = new Toast(App.getContext());
                toast.setGravity(Gravity.CENTER, 0, 0);
                // 默认显示toast
                if (shortOrLong == null || shortOrLong.length == 0) {
                    toast.setDuration(Toast.LENGTH_SHORT);
                } else {
                    toast.setDuration(shortOrLong[0]);
                }
                toast.setView(layout);
                toast.show();
            }
        });
    }
}
